// --------------------------------------------------------------------------------------------------------------------- 
// <copyright file="AggregateRulesCollection.cs" company="Scrum for Team System">
//   None
// </copyright>
// <summary>
//   Defines the SourceLinkDirection type.
// </summary>
// ---------------------------------------------------------------------------------------------------------------------
namespace ScrumForTeamSystem.EventService.AggregationService.DataObjects
{
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Xml.Serialization;

    using Infrastructure;
    using Infrastructure.Interfaces;

    /// <summary>
    /// Defines the AggregateRulesCollection type.
    /// </summary>
    [XmlRoot(Namespace = "http://schemas.ScrumForTeamSystem.com/AggregationService/RulesCollection")]
    public class AggregateRulesCollection : Collection<AggregateRule>, IRulesCollection<AggregateRule>
    {
        /// <summary>
        /// Gets the matching rules.
        /// </summary>
        /// <param name="workItemChangedEvent">The work item changed event.</param>
        /// <returns>A collection of matching rules.</returns>
        public IEnumerable<AggregateRule> GetMatchingRules(WorkItemChangedEvent workItemChangedEvent)
        {
            var workItemTypeName = workItemChangedEvent.GetStringFieldValue(ConstantStrings.WorkItemTypeCoreField);

            if (workItemChangedEvent.HasLinkChanges() || workItemChangedEvent.HasPathChanges())
            {
                return this.GetAllRulesThatContain(workItemTypeName);
            }

            return
                    this.Where(
                            r =>
                            r.WorkItemType.Source.Equals(workItemTypeName)
                            &&
                            (workItemChangedEvent.HasAlteredInclusionStatus(r)
                             || workItemChangedEvent.HasAlteredSourceFieldName(r)));
        }

        /// <summary>
        /// Gets all rules that contain the specfied work item type name.
        /// </summary>
        /// <param name="workItemTypeName">Name of the work item type.</param>
        /// <returns>All rules that contain the specfied work item type name.</returns>
        private IEnumerable<AggregateRule> GetAllRulesThatContain(string workItemTypeName)
        {
            return
                    this.Where(
                            r =>
                            r.WorkItemType.Source.Equals(workItemTypeName)
                            || r.WorkItemType.Target.Equals(workItemTypeName));
        }
    }
}